import MetaballMgr from "./MetaballMgr";
import Model from "./Model";
import Config from "./Config";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Game extends cc.Component {

    private timeArray = [2.7,3,2.8,4.3,4.5,5,4.8,7,2.3,3.4,0.5,2.2,1.2,1.6,1.5,1,3.5,1]

    @property(cc.Prefab)
    Ball: cc.Prefab = null;

    @property(cc.Prefab)
    Cup: cc.Prefab = null;

    @property(cc.Prefab)
    Wall: cc.Prefab = null;

    @property(cc.Node)
    wallContainer: cc.Node = null;

    @property(cc.Node)
    content: cc.Node = null;

    @property(cc.Node)
    topNode: cc.Node = null;

    @property(cc.Node)
    wrold: cc.Node = null;

    @property(cc.Node)
    drawMgr: cc.Node = null;

    @property(cc.Node)
    faceNode: cc.Node = null;

    @property(cc.Prefab)
    TopUI: cc.Prefab = null;

    @property(cc.Prefab)
    BottomUI: cc.Prefab = null;

    @property(cc.Node)
    timeLabel: cc.Node = null;


    createDelay: number = 0.05;
    createDelayTime: number = 1;
    canCreate = false;
    touchX: number = 0
    touchY: number = 0


    @property(cc.Node)
    countDownNode: cc.Node = null;
    countDownTime: number = 0

    linePosY: number = -250
    startCheckY: number = -212

    lock: boolean = false;
    faceChange: boolean = false;

    curCup: cc.Node;

    @property({type:cc.AudioClip})
    waterClip: cc.AudioClip = null;;

    waterSoundDelay = 0.2;
    waterSoundDelayCount = 10;

    waters: Array<cc.Node> = []

    private scTime = 0
    private isJiLiBoFang = false;
    callback = function () {
        this.scTime = this.scTime + 0.1;
        if(this.timeArray[Model.game.selectedLevel-1] < this.scTime){
            this.timeLabel.getComponent(cc.Label).string = '停止';
            // this.lock = true
            // this.canCreate = false;
        }else{
            this.timeLabel.getComponent(cc.Label).string = this.scTime.toFixed(1)+'';
        }
    }

    onLoad() {
        this.timeLabel.active = false;

        Config.init()
        //开启物理效果
        cc.director.getPhysicsManager().enabled = true
        cc.director.getPhysicsManager().gravity = new cc.Vec2(0, -500);
        // cc.director.getPhysicsManager().debugDrawFlags = cc.PhysicsManager.DrawBits.e_jointBit | cc.PhysicsManager.DrawBits.e_shapeBit;

        // this.schedule(this.addBall,0.2);
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);


        var top = cc.instantiate(this.TopUI)
        this.node.addChild(top)


        this.drawMgr.getComponent(MetaballMgr).waters = this.waters;
        this.node.getChildByName('gameTip').active = Model.game.selectedLevel == 1
        this.createWorld()

    }

    createWorld() {
        //cup
        var level = 1;
        var data = Config.preciseLevels[Model.game.selectedLevel]
        var cup = cc.instantiate(this.Cup);
        this.content.addChild(cup, 0)
        cup.x = data[1]
        cup.y = data[2]
        var cupData = Config.cupDatas[Model.game.selectedLevel]
        for (var i = 0; i < cupData.polygonColliderList.length; i++) {
            cup.addComponent(cc.PhysicsPolygonCollider)
        }
        var self = this;
        cc.loader.loadRes("textures/cup/cup" + data[0], cc.SpriteFrame, function (err, spriteFrame) {
            cup.getComponent(cc.Sprite).spriteFrame = spriteFrame;
        });
        //添加改变后，要用apply
        var allCollider = cup.getComponents(cc.PhysicsPolygonCollider);
        for (i = 0; i < allCollider.length; i++) {
            var tempC = allCollider[i];
            tempC.points = cupData.polygonColliderList[i]
            tempC.apply()
        }
        this.linePosY = cupData.linePosY + cup.y;

        this.curCup = cup
        //face

        this.faceNode.active = true
        this.faceNode.x = cup.x + cupData.faceOffsetX
        this.faceNode.y = cup.y + cupData.faceoffsetY
        this.faceNode.scale = cupData.faceScale
    }
    createWall(x: number, y: number, w: number, h: number, angle: number) {
        var wall: cc.Node = cc.instantiate(this.Wall)
        wall.width = w;
        wall.height = h;
        wall.x = x
        wall.y = y
        wall.angle = -angle;
        wall.getComponent(cc.PhysicsBoxCollider).size = cc.size(w, h);
        this.wallContainer.addChild(wall)
    }
    onTouchStart(e) {
        if(this.isJiLiBoFang){
            this.schedule(this.callback, 0.1);
        }
        if (this.lock) return;
        var pos = e.getLocation();
        pos = this.node.convertToNodeSpaceAR(pos)
        this.touchX = pos.x;
        this.touchY = pos.y;
        //this.scheduleOnce(this.startCreateBall,0.1)
        this.canCreate = true;

    }
    onTouchEnd(e) {
        if(this.isJiLiBoFang){
            this.scTime = 0;
            this.unschedule(this.callback);
        }
        // else{
            this.lock = true
            this.canCreate = false;
        // }
    }
    startCreateBall() {
        this.canCreate = true;
    }

    start() {

    }
    addBall(x: number, y: number) {
        var ball = cc.instantiate(this.Ball);
        ball.x = x
        ball.y = y
        ball.getComponent(cc.PhysicsCircleCollider).restitution = 0.2
        ball.getComponent(cc.PhysicsCircleCollider).apply()

        this.wrold.addChild(ball);
        this.waters.push(ball);


    }
    totalBall = 0
    update(dt) {
        if (this.canCreate) {
            this.createDelayTime += dt;
            if (this.createDelayTime >= this.createDelay) {
                this.createDelayTime = 0
                // if (this.totalBall < 50) {
                this.totalBall++
                this.addBall(-135 + 20 - Math.random() * 40, 290);

                this.waterSoundDelayCount += dt
                if (this.waterSoundDelayCount > this.waterSoundDelay) {
                    this.waterSoundDelayCount = 0
                    cc.audioEngine.playEffect(this.waterClip, false)
                }
                // }
            }
        }

        this.drawMgr.getComponent(MetaballMgr).draw()

        if (this.lock && this.countDownNode.active == false) {
            this.checkGame()
        }
    }
    checkGame() {

        if (this.checkAllDown()) {
            console.log('检测');
            this.countDownTime = 3
            this.countDownNode.active = true;
            this.schedule(this.startCountDown, 1)
        }

        if (this.faceChange == false) {
            for (var temp of this.waters) {
                if (temp.y <= this.linePosY) {
                    this.faceChange = true;
                    this.showFace(1)
                    break;
                }
            }
        }
    }

    startCountDown() {
        this.countDownNode.getChildByName('p0').active = false
        this.countDownNode.getChildByName('p1').active = false
        this.countDownNode.getChildByName('p2').active = false
        this.countDownNode.getChildByName('p3').active = false
        this.countDownTime--;

        this.countDownNode.getChildByName('p' + this.countDownTime).active = true
        if (this.countDownTime <= 0) {
            this.countDownNode.getChildByName('p0').active = false
            this.unschedule(this.startCountDown)
            this.schedule(this.checkBallSleep, 0.016)
        }
    }
    //判断所有的是否已经下落，开始检测
    checkAllDown() {
        var bol = true;
        for (var temp of this.waters) {
            if (temp.y > this.startCheckY) {
                bol = false;
                break

            }
        }
        return bol
    }
    checkBallSleep() {
        var bol = true;
        var goalCount = 0
        for (var temp of this.waters) {
            //暂时不检测休眠
            // if (temp.getComponent(cc.RigidBody).awake == true) {
            //     bol = false;
            //     break;
            // }

            if (temp.y >= this.linePosY) {
                goalCount++;
            }

        }

        if (bol) {
            console.log('全部休眠')
            this.unschedule(this.checkBallSleep);
            if (goalCount >= 2) {
                console.log('游戏胜利')
                Model.game.win = true
                Model.game.preciseLevel++
                this.showFace(2)
                this.scheduleOnce(this.delayShowEnd.bind(this), 1)
            } else {
                Model.game.win = false;
                console.log('游戏失败')
                this.showFace(0)
                this.scheduleOnce(this.delayShowEnd.bind(this), 1)
            }
        }
    }
    delayShowEnd() {
        cc.director.loadScene('gameEnd')
    }
    showFace(type: number) {
        this.faceNode.getChildByName('facenormal').active = false;
        this.faceNode.getChildByName('facewin').active = false;
        this.faceNode.getChildByName('facelose').active = false;
        if (type == 2) {
            this.faceNode.getChildByName('facewin').active = true;
        } else if (type == 1) {
            this.faceNode.getChildByName('facelose').active = true;
        } else if (type == 0) {
            this.faceNode.getChildByName('facenormal').active = true;
        }
    }

    retryClick() {
        cc.director.loadScene('game')
    }
    onBackClick() {
        cc.director.loadScene('menu')
    }

    onBtn(){
        console.log("@@@@@@@@@@@@播放激励视频")
        this.isJiLiBoFang = true;
        this.timeLabel.active = true;
    }
}


//1-2  = 3
//3   = 3.5
//4 5     = 4
//6    =4.5
